<template>
  <div>
    <el-dialog center :title="isAdd ? '添加商品分类' : '编辑商品分类'" :visible.sync="isShow" :close-on-press-escape="false"
      :before-close="cancel">
      <el-form :model="cate_info" :rules="rules" ref="userinfo">
        <el-form-item prop="pid" label="上级分类" :label-width="formLabelWidth">
          <el-select v-model="cate_info.pid" placeholder="请选择">
            <el-option label="顶级分类" :value="0"></el-option>
            <el-option v-for="item in catelist" :key="item.id" :value="item.id" :label="item.catename"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="catename" label="商品分类名称" :label-width="formLabelWidth">
          <el-input v-model="cate_info.catename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" v-if="cate_info.pid != 0" :label-width="formLabelWidth">
          <!-- 图片上传组件
          action	必选参数，上传的地址
          list-type	文件列表的类型	string	text/picture/picture-card
          on-preview	点击文件列表中已上传的文件时的钩子	function(file)
          on-remove	文件列表移除文件时的钩子	function(file, fileList)
          on-change	文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用	function(file, fileList)
          file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]	array
          on-exceed	文件超出个数限制时的钩子	function(files, fileList)
          -->
          <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="onRemove"
            :on-change="changeFile" :file-list="fileList" :limit="1" :on-exceed="handleExceed">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- 图片预览 -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch v-model="cate_info.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
            :inactive-value="2">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="comfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cateAdd, cateInfo, cateEdit } from "../../request/api";
//引入辅助性函数
import { mapActions, mapGetters } from "vuex";
export default {
  props: ["isShow", "isAdd"],
  data() {
    return {
      cate_info: {
        pid: 0, //上级分类编号
        catename: "", //商品分类名称
        img: "", //图片
        status: 1, //状态   1正常2禁用   number类型
      },
      formLabelWidth: "120px",
      dialogVisible: false, //是否渲染图片弹框
      dialogImageUrl: "", //图片地址
      fileList: [],
      rules: {
        catename: [
          { required: true, message: "请输入商品分类名称", trigger: "blur" },
          {
            min: 2,
            max: 6,
            message: "长度在 2 到 6 个字符",
            trigger: "blur",
          },
        ],
        pid: [
          { required: true, message: "请选择上级商品分类", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getCate()
  },
  computed: {
    ...mapGetters({
      catelist: 'cate/getCalist'
    })
  },
  methods: {
    ...mapActions({
      getCate: 'cate/changeCateAction'
    }),
    //封装一个取消事件
    cancel() {
      this.$emit("cancel", false);
      //并清空
      this.reset();
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    },
    // 图片预览
    onPreview(file) {
      //给预览图片赋值
      this.dialogImageUrl = file.url;
      //打开弹框
      this.dialogVisible = true;
    },
    // 文件修改时触发
    changeFile(file, filelist) {
      console.log(file, filelist, "change");
      this.cate_info.img = file.raw;
    },
    // 移除
    onRemove(file, filelist) {
      console.log(file, filelist, "移除");
    },
    //封装一个重置事件
    reset() {
      this.cate_info = {
        pid: 0, //上级分类编号
        catename: "", //商品分类名称
        img: "", //图片
        status: 1, //状态   1正常2禁用   number类型
      };
      //清空表单验证
      this.$refs.userinfo.resetFields();
      //清空文件列表
      this.fileList = [];
    },
    //封装一个函数用来数据回显
    lookup(id) {
      //调用一条数据查询
      cateInfo({ id }).then(res => {
        if (res.data.code == 200) {
          this.cate_info = res.data.list;
          this.cate_info.id = id;
          this.fileList = [{ url: this.$img + res.data.list.img }]
        }
      })

    },
    //封装一个确定事件
    comfirm() {
      this.$refs.userinfo.validate((val) => {
        if (val) {
          //判断是否为添加还是编辑
          if (this.isAdd) {
            // console.log(this.cate_info,'表单对象');
            //添加接口
            cateAdd(this.cate_info).then(res => {
              if (res.data.code == 200) {
                //添加成功
                this.$message.success(res.data.msg);
                this.cancel()
                this.getCate()
              } else {
                this.$message.error(res.data.msg);
              }
            })

          } else {
            //编辑接口
            cateEdit(this.cate_info).then(res => {
              if (res.data.code == 200) {
                //添加成功
                this.$message.success(res.data.msg);
                this.cancel()
                this.getCate()
              } else {
                this.$message.error(res.data.msg);
              }
            })
          }
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
